<?php

/**
 * User module for the Yii Framework
 * 
 * @author Martin Gelder <darkspotinthecorner@gmail.com> 
 * @link http://www.dsitc.de
 * @license http://www.opensource.org/licenses/bsd-license.php
 */

class UserModule extends CWebModule
{
	const REGISTRATION_VALIDATION_TYPE_DIRECT      = 1;
	const REGISTRATION_VALIDATION_TYPE_EMAIL       = 2;
	const REGISTRATION_VALIDATION_TYPE_ADMIN       = 3;
	const REGISTRATION_VALIDATION_TYPE_EMAIL_ADMIN = 4;
	
	public $defaultController = 'userlist';
	
	public $registrationValidationType = self::REGISTRATION_VALIDATION_TYPE_EMAIL;
	
	public $urls = array(
		'base'           => array('/user'),
		'activation'     => array('/user/activation/index'),
		'registration'   => array('/user/registration/index'),
		'recovery'       => array('/user/recovery/index'),
		'recoveryCommit' => array('/user/recovery/commit'),
		'login'          => array('/user/login/index'),
		'profile'        => array('/user/profile/view'),
		'logout'         => array('/user/logout/index'),
		'loggedIn'       => array('/user'),
		'loggedOut'      => array('/user'),
	);
	
	public $security = array(
		'secret'     => 'tävö+Nvh<üTC}p%*&@BW9(0&K0kMtküO',
		'stretching' => 12,
		'portable'   => false,
		'captcha'    => array('registration', 'recovery'),
		'timeout'    => array(
			'activation' => 108000, // 30 Minutes
			'recovery'   => 36000,  // 10 Minutes
		),
	);
	
	public $tables = array(
		'users' => '{{Users}}'
	);
	
	public $settings = array(
		'cookie' => array(
			'duration' => 2592000,
		),
		'password' => array(
			'minLength' => 4
		),
		'alias' => array(
			'minLength' => 3,
			'maxLength' => 24,
		),
	);
	
	public $hasher = null;
	
	public function init()
	{
		$this->setImport(array(
			'user.models.*',
			'user.components.*',
		));
		
		$this->hasher = new PasswordHash($this->getCryptStretching(), $this->security['portable']);
	}
	
	public static function t($string = '', $params = array(), $dictionary = 'UserModule.core')
	{
		return Yii::t($dictionary, $string, $params);
	}
	
	public function getCryptStretching()
	{
		return max(8, intval($this->security['stretching']));
	}
	
	public function salt($string, $add = '')
	{
		return $string . $this->security['secret'] . $add;
	}
	
	public function encrypt($string = '')
	{
		return $this->hasher->HashPassword($string);
	}
	
	public function checkAgainstEncrypted($raw, $encrypted)
	{
		return $this->hasher->CheckPassword($raw, $encrypted);
	}
	
	public function doCaptcha($place = '')
	{
		if(!extension_loaded('gd'))
		{
			return false;
		}
		if(in_array($place, Yii::app()->getModule('user')->security['captcha']))
		{
			return true;
		}
		return false;
	}
	
	public function isAdmin()
	{
		if(Yii::app()->user->isGuest)
		{
			return false;
		}
		else
		{
			if(($this->user() != false) && ($this->user()->admin))
			{
				return true;
			}
		}
		return false;
	}

	public function sendMail($email, $subject, $message)
	{
    	$email_noreply   = Yii::app()->params['email.noreply'];
		$email_community = Yii::app()->params['email.community'];
	    $headers    = "MIME-Version: 1.0\r\nFrom: " . $email_noreply . "\r\nReply-To: " . $email_community . "\r\nContent-Type: text/html; charset=utf-8";
	    $message    = wordwrap($message, 70);
	    $message    = str_replace("\n.", "\n..", $message);
	    return mail(
			$email,
			('=?UTF-8?B?' . base64_encode($subject) . '?='),
			$message,
			$headers
		);
	}
	
	public function user($id = 0)
	{
		if($id)
		{
			return User::model()->active()->findbyPk($id);
		}
		else
		{
			if(!Yii::app()->user->isGuest)
			{
				return User::model()->active()->findbyPk(Yii::app()->user->id);
			}
		}
		return false;
	}
	
}
